#!/bin/sh

n=$1
v=$2
g=infra

Extract() {
	if [ -d ~/Packages/$n ]; then
		rm -rf ~/Packages/$n
		mkdir -p ~/Packages/$n
	else
		mkdir -p ~/Packages/$n
	fi

	cd ~/Packages/$n
	tar -xf ~/.repo/infra/$n-$v-pkg.txz .
}

FileList() {
	Extract

	FileList=/home/ahc/FileLists/$n-filelist.txt
	if [ -f $FileList ]; then rm -rf $FileList; fi
	lst=$(find . -type f | sed 's/.\//'$n' \//' | sort| cat -n)
	for i in "$lst"; do echo "$i" >> $FileList; done
	sed -e 's/^\s\+//' -e 's/\t/ /' -i $FileList
}

echo "info: inserting: $n-$v"
FileList

sqlite3 ~/.repo/global.sqlite "delete from packages where name = '$n';"
sqlite3 ~/.repo/global.sqlite "insert into packages (name, version, pkgrp) values('$n', '$v', '$g');"

sqlite3 ~/.repo/global.sqlite "delete from filelist where name = '$n';"
sqlite3 -batch ~/.repo/global.sqlite <<EOF
.separator ' '
.import $FileList filelist
EOF
echo "      done"